package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

//@ControllerAdvice(annotations = {RestController.class, Controller.class})//默认所有控制的抛出的异常都会在这个类进行处理
//@ResponseBody
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     *处理重复保存的异常
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.info(ex.getMessage());
        //判断异常是否存在为了避免空指针异常
        if (ex.getMessage().contains("Duplicate entry")){
            //切割异常信息
            String[] s = ex.getMessage().split(" ");
            String msg=s[2]+"已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        log.info(ex.getMessage());
        return R.error(ex.getMessage());
    }

}
